﻿using System.Linq;
using System.Text;
using System.Collections.Generic;
using Microsoft.SqlServer.Dts.Runtime;

namespace NazTek.Documenter.Ssis.Control
{
    internal class SsisTaskManager : List<ISsisTask>
    {
        internal SsisPackage Parent { get; set; }
        internal SsisTaskManager(IDTSSequence package, SsisPackage parent)
        {
            Parent = parent;
            ConstraintDictionary = new Dictionary<string, List<string>>();
            foreach (var cnstr in package.PrecedenceConstraints.OfType<PrecedenceConstraint>())
            {
                var ce = cnstr.ConstrainedExecutable as TaskHost;
                var pe = cnstr.PrecedenceExecutable as TaskHost;
                if (ce == null) 
                    continue;
                if (!ConstraintDictionary.ContainsKey(ce.Name))
                    ConstraintDictionary[ce.Name] = new List<string>();
                if (pe != null)
                    ConstraintDictionary[ce.Name].Add(pe.Name);
            }
            PackageTasks = package.Executables.OfType<TaskHost>().ToList();

            var independentTasks = PackageTasks.Where(tsk => !ConstraintDictionary.Keys.Contains(tsk.Name));
            independentTasks.ToList().ForEach(t =>
            {
                var task = SsisTaskBuilder.BuildTask(t, parent);
                Add(task);
                AssignChildren(task);
            });
        }
        internal string BuildDoc(string pkgTitle)
        {
            var doc = new StringBuilder();
            foreach (var tsk in this)
                tsk.BuildDoc(doc);
            return string.Format(
                "<LINK REL=\"StyleSheet\" HREF=\"Code.css\" TYPE=\"text/css\"><h3>SSIS Package<br />{0}</h3>{1}<ol>{2}</ol>",
                pkgTitle, Parent.Connections.GetDoc(), doc);
        }

        private List<TaskHost> PackageTasks { get; set; }
        private Dictionary<string, List<string>> ConstraintDictionary { get; set; }

        private void AssignChildren(ISsisTask task)
        {
            var children = GetChildrenTasks(task.Name, PackageTasks, ConstraintDictionary);
            if (children == null || children.Count <= 0) 
                return;
            task.Children = children;
            children.ForEach(AssignChildren);
        }
        private List<ISsisTask> GetChildrenTasks(string taskName, IEnumerable<TaskHost> pkgTasks, Dictionary<string, List<string>> constraintDictionary)
        {
            return constraintDictionary.Where(itm => itm.Value.Contains(taskName))
                .Select(itm => SsisTaskBuilder.BuildTask(pkgTasks.FirstOrDefault(t => t.Name == itm.Key), Parent)).ToList();
        }
    }
}